package com.starhub.common.security.handle;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义权限不足处理器（返回 JSON 格式错误信息）
 */
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {

    private final ObjectMapper objectMapper = new ObjectMapper();


    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        // 1. 设置响应状态码和内容类型
//        response.setStatus(HttpStatus.FORBIDDEN.value());
//        response.setContentType("application/json;charset=UTF-8");
//
//        // 2. 构建错误响应内容
//        Map<String, Object> errorResponse = new HashMap<>();
//        errorResponse.put("code", 403);
//        errorResponse.put("message", "权限不足，禁止访问");
//        errorResponse.put("path", request.getRequestURI());
//        errorResponse.put("timestamp", System.currentTimeMillis());
//
//        // 3. 记录访问日志（可选）
//        logAccessDeniedEvent(request, accessDeniedException);
//
//        // 4. 返回 JSON 响应
//        response.getWriter().write(
//                objectMapper.writeValueAsString(errorResponse)
//        );
    }

    /**
     * 记录权限拒绝事件
     */
    private void logAccessDeniedEvent(HttpServletRequest request,
                                      AccessDeniedException ex) {
        String user = request.getRemoteUser(); // 获取当前用户
        String method = request.getMethod();
        String path = request.getRequestURI();

        // 示例日志格式：
        // [FORBIDDEN] 用户[admin]尝试访问[GET /api/users]失败：权限不足
        String logMsg = String.format(
                "[FORBIDDEN] 用户[%s]尝试访问[%s %s]失败：%s",
                user != null ? user : "匿名用户",
                method,
                path,
                ex.getMessage()
        );
        System.out.println(logMsg); // 替换为实际日志框架调用
    }
}
